﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Net.Sockets;
using HCService.Client;
using System.Threading;

namespace HCService.Service
{
	public class ServiceBase
	{
		Socket ServerSocket { get; set; }
		
		protected Action<byte[]> msgHandle;

		//protected List<ClientBase> lstConnectClient = new List<ClientBase>();
		protected List<ClientStream> lstConnectClient = new List<ClientStream>();

		public ServiceBase(Action<byte[]> handle)
		{
			this.msgHandle = handle;
		}

		public void Connect(string ip, int  port)
		{
			IPAddress ipAdd;
			if (string.IsNullOrEmpty(ip))
				ipAdd = IPAddress.Any;
			else
				ipAdd = IPAddress.Parse(ip);
			if (port < 0) port = 0;
			IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, port);
			ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
			
			//绑定端口并接受一定数量的客户端Socket连接
			ServerSocket.Bind(endPoint);
			ServerSocket.Listen(int.MaxValue);
			//Console.WriteLine("连接");
			//启动接收Client响应
			ServerSocket.BeginAccept(new AsyncCallback(ReceiveCallback), this);

			Console.ReadKey();
		}

		protected void ReceiveCallback(IAsyncResult iar)
		{
			Socket cntSocket = ServerSocket.EndAccept(iar);
			//ClientBase tmpClient = new ClientBase(cntSocket);
			//this.lstConnectClient.Add(tmpClient);

			ClientStream tempClient = new ClientStream(this, cntSocket);
			lstConnectClient.Add(tempClient);
			Console.WriteLine(cntSocket.RemoteEndPoint.ToString());
			//启动监听下一个客户端连接
			ServerSocket.BeginAccept(ReceiveCallback, this);
		}

		public void AbandonClient(ClientStream client)
		{
			//放弃持有改客户端
			lstConnectClient.Remove(client);
			Console.WriteLine("Abandon");
		}

	}
}
